<?php

namespace App\Admin\Actions;

use App\Constant\Enum;
use App\Models\AdrewardDetail;
use App\Models\Setting;
use App\Models\UserWithdraw;
use App\Services\Withdraw\UserWithdrawService;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;


class ReviewForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $withdrawId = $input['withdraw_id'] ?? 0;
        $action = $input['status'] ?? '';
        $remark = $input['remark'] ?? '';

        if (!in_array($action, [
            Enum::WITHDRAW_STATUS_APPROVED,
            Enum::WITHDRAW_STATUS_REJECTED,
        ])) {
            return response()->json([
                'code' => 400,
                'message' => '审核状态无效'
            ]);
        }

        $userWithdraw = UserWithdraw::query()->find($withdrawId);
        if (!$userWithdraw) {
            return response()->json([
                'code' => 400,
                'message' => '提现申请不存在'
            ]);
        }


        try {
            if ($action == Enum::WITHDRAW_STATUS_APPROVED) {
                UserWithdrawService::approve($userWithdraw, $remark, Admin::user()->id);
            } else {
                UserWithdrawService::reject($userWithdraw, $remark, Admin::user()->id);
            }
            return response()->json([
                'code' => 200,
                'message' => '审核成功'
            ]);
        } catch (\Exception $exception) {
            return response()->json([
                'code' => 400,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    public function form()
    {
        $id = $this->payload['key'];
        $withdraw = UserWithdraw::query()->findOrFail($id);
        $userId = $withdraw->getAttribute('user_id');
        $maxEcpm = Setting::get('max_ecpm') ?? 0;
        if ($maxEcpm > 0) {
            $count = AdrewardDetail::query()
                ->where('user_id', $userId)
                ->where('adtype_id', '!=', 0)
                ->where('ecpm', '>=', $maxEcpm)
                ->count();
            $count = sprintf("%s 条收益明细异常！", $count ?? 0);
            $url = admin_url("adreward-details?user_id={$userId}&_sort[column]=ecpm&_sort[type]=desc");
            $help = "ECPM最大限额：{$maxEcpm}，<a href='{$url}' target='_blank'>查看详情</a>";
        } else {
            $count = '暂无限制ECPM，需要核对收益请查看 收益明细';
            $help = "ECPM最大限额：{$maxEcpm}";
        }
        $this->text('message', 'ECPM超过限额数量')
            ->value($count)
            ->help($help)
            ->readOnly();
        $this->divider();
        $this->hidden('withdraw_id')->value($this->payload['key']);
        $this->radio('status', '结果')->options([
            Enum::WITHDRAW_STATUS_APPROVED => '通过',
            Enum::WITHDRAW_STATUS_REJECTED => '拒绝',
        ])->required();
        $this->textarea('remark', '备注');
    }

    /**
     * 设置表单保存成功后执行的JS
     *
     * @return string|void
     */
    protected function savedScript()
    {
        return <<<JS
        if (data.code != 200) {
            Dcat.error(data.message);
            return false;
        }

        Dcat.success(data.message);
        Dcat.reload();

        return false;
JS;
    }

    /**
     * 设置表单保存失败后执行的JS
     *
     * @return string|void
     */
    protected function errorScript()
    {
        return <<<JS
        var errorData = JSON.parse(response.responseText);
        if (errorData) {
            if (errorData.message) {
                Dcat.error(errorData.message);
            } else {
                Dcat.error("审核结果必填");
            }
        } else {
            console.log('提交出错', response.responseText);
        }
        // 终止后续逻辑执行（默认逻辑）
        return false;
JS;
    }
}
